import {
  fetchPerson
} from '../../../services/usercenter/fetchPerson';
import {
  getUserInfo
} from '../../../services/usercenter/user';
import {
  phoneEncryption
} from '../../../utils/util';
import Toast from 'tdesign-miniprogram/toast/index';
import {
  updateUser
} from '../../../services/usercenter/user';

import {
  baseUrl
} from '../../../config/index'
Page({
  data: {
    personInfo: {
      avatarUrl: '',
      nickName: '',
      gender: 0,
      phoneNumber: '',
    },
    showUnbindConfirm: false,
    pickerOptions: [{
        name: '男',
        code: '1',
      },
      {
        name: '女',
        code: '2',
      },
    ],
    typeVisible: false,
    genderMap: ['', '男', '女'],
  },
  onShow(){
    console.log("show");
    this.init();
  },
  onLoad() {
    // this.init();
  },
  init() {
    console.log("个人资料页面刷新");
    this.fetchData();
  },
  openUnbindConfirm() {
    // 
    console.log("点击了切换账号登录");
    wx.navigateTo({
      url: '/pages/login/index',
    })
  },
  fetchData() {

    // 这里是获取用户信息
    getUserInfo().then(res => {
      console.log(res.data);
      const personInfo = {
        avatarUrl: res.data.data.avatar,
        nickName: res.data.data.username,
        phoneNumber: res.data.data.phone,
        gender: res.data.data.sex,
      }
      this.setData({
        personInfo,
      });
    });
  },
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;
    const {
      nickName
    } = this.data.personInfo;

    switch (dataset.type) {
      case 'gender':
        this.setData({
          typeVisible: true,
        });
        break;
      case 'name':
        wx.navigateTo({
          url: `/pages/usercenter/name-edit/index?name=${nickName}`,
        });
        break;
      case 'avatarUrl':
        // 修改头像
        this.toModifyAvatar();
        break;
      default: {
        break;
      }
    }
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {

    var that = this
    // 确认修改性别
    const {
      value
    } = e.detail;
    console.log(e);
    this.setData({
        typeVisible: false,
        'personInfo.gender': value,
      },
      () => {
        updateUser({
          gender: value
        }).then(res => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: res.data.message,
            theme: 'success',
          });
          that.setData({
            'personInfo.gender':value
          })
        }).catch(error => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: "修改性别失败",
            theme: 'error',
          });
        })
      },
    );
  },
  // 修改头像
  async toModifyAvatar() {
    var that =this;
    try {
      const path = await new Promise((resolve, reject) => {
        wx.chooseMedia({
          count: 1,
          sizeType: ['compressed'],
          mediaType: ['image'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            console.log(res);
            const {
              tempFilePath,
              size
            } = res.tempFiles[0];
            if (size <= 10485760) {
              // Upload image to server
              console.log("开始上传图片" + tempFilePath);
              wx.uploadFile({
                url: baseUrl + "oss/upload",
                filePath: tempFilePath,
                name: 'file',
                success: function (res) {
                  const data = JSON.parse(res.data)
                  console.log(data);
                  console.log(data.data);
                  resolve(data.data);
                  // do something
                },
                fail: function (error) {
                  reject({
                    errMsg: '上传失败'
                  });
                }
              })
            } else {
              reject({
                errMsg: '图片大小超出限制，请重新上传'
              });
            }
          },
          fail: (err) => reject(err),
        });
      });
      console.log("修改图像" + path);
      updateUser({
        avatarUrl: path
      }).then(res => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: "修改头像成功",
          theme: 'error',
        });
        that.setData({
          'personInfo.avatarUrl':path
        })
      }).catch(error => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: error.errMsg || error.msg || '修改头像出错了',
          theme: 'error',
        });
      })
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.errMsg || error.msg || '修改头像出错了',
        theme: 'error',
      });
    }
  },
});